import 'package:chop/Model/DistanceEntity.dart';
import 'package:chop/Model/address_entity.dart';
import 'package:chop/Model/order_entity.dart';
import 'package:chop/Model/priceEntity.dart';
import 'package:chop/common/DateUtils.dart';
import 'package:chop/common/DioUtils.dart';
import 'package:chop/common/SPUtils.dart';
import 'package:chop/common/StringUtils.dart';
//import 'package:chop/view/pay/pay_list.dart';
//import 'package:chop/view/sendyou/send_address_page.dart';
import 'package:chop/widgets/TextSizeWidget.dart';
import 'package:chop/widgets/ToastWidget.dart';
import 'package:chop/widgets/appBar.dart';
import 'package:chop/widgets/loadingDialog.dart';
import 'package:chop/widgets/orderWidget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:loading_animations/loading_animations.dart';

class Delivery_order extends StatefulWidget {
  final AdrEntityData begin; //起始地址
  final AdrEntityData end;

  const Delivery_order({Key key, this.begin, this.end})
      : super(key: key); //结束地址
  @override
  _Delivery_orderState createState() => _Delivery_orderState();
}

class _Delivery_orderState extends State<Delivery_order> {
  AdrEntityData begin; //起始地址
  AdrEntityData end; //结束地址
  TextEditingController _remarks; //备注
  String range;
  bool isNetWorkBad = false;
  double price;
  String rader = "0";
  String longTime;
  DateTime n = DateTime.now();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    this.begin = widget.begin;
    this.end = widget.end;
    _remarks = TextEditingController();
    _getDistance();
  }

  int choose;



  //获取距离
  void _getDistance() {
    DioUtils.getTime(
            Position(
                longitude: double.parse(begin.lng),
                latitude: double.parse(begin.lat)),
            Position(
                latitude: double.parse(end.lat),
                longitude: double.parse(end.lng)))
        .then((Map m) {
      if (m['code'] == 500) {
        Toast.toast(context,
            msg: "连接服务器失败",
            bgColor: Colors.redAccent,
            position: ToastPostion.bottom);
        setState(() {
          isNetWorkBad = true;
        });
      } else {
        DistanceEntity distanceEntity = DistanceEntity.fromJson(m);
        range = distanceEntity.rows[0].elements[0].distance.text.substring(
            0, distanceEntity.rows[0].elements[0].distance.text.length - 3);
        longTime =
            DateUtils.getMins(distanceEntity.rows[0].elements[0].duration.text);
        var now = DateTime.now();
        n = now.add(Duration(minutes: int.parse(longTime) + 20));
        print("需要的时间：——————————————————————》${n}");
        DioUtils.getPrice(range).then((priceEntity price_entity) {
          setState(() {
            isNetWorkBad = true;
            price = price_entity.price;
          });
        });
      }
    });
  }

  Widget getBody() {
    if (isNetWorkBad) {
      if(price == null){
        return Center(child: FixedSizeText("连接服务器失败"),);
      }else{
        return ListView(
          children: <Widget>[
            // 地址信息
            getColumn(
              "地址信息",
              child: Column(
                children: <Widget>[
                  getAddress(begin,
                      iconText: "买",
                      iconBgColor: Colors.blue,
                      iconTextStyle: TextStyle(
                        color: Colors.white,
                      ), callback: () async {
//                      var result = await Get.to(sendAddressPage(isSend: true,));
//                      if(result != null){
//                        print(result);
//                        if(StringUtils.isNotNull(end.address)){
//                          begin = result;
//                          _getDistance();
//                        }else{
//                          setState(() {
//                            begin = result;
//                          });
//                        }
//                      }
                      }),
                  Container(
                    height: 10,
                  ),
                  getAddress(end,
                      iconText: "收",
                      iconBgColor: Colors.green,
                      iconTextStyle: TextStyle(
                        color: Colors.white,
                      ), callback: () async {
//                      var result = await Get.to(sendAddressPage(isSend: false,));
//                      if(result != null){
//                        print(result);
//                        if(StringUtils.isNotNull(begin.address)){
//                          end = result;
//                          _getDistance();
//                        }else{
//                          setState(() {
//                            end = result;
//                          });
//                        }
//                      }
                      }),
                ],
              ),
            ),
            getColumn("选择载具",
                child: Row(
                  children: <Widget>[
                    Expanded(
                        child: Row(
                          children: <Widget>[
                            Radio(
                                value: "0",
                                groupValue: rader,
                                onChanged: (val) {
                                  setState(() {
                                    rader = val;
                                  });
                                }),
                            FixedSizeText("自行车")
                          ],
                        )),
                    Expanded(
                        child: Row(
                          children: <Widget>[
                            Radio(
                                value: "1",
                                groupValue: rader,
                                onChanged: (val) {
                                  setState(() {
                                    rader = val;
                                  });
                                }),
                            FixedSizeText("汽车")
                          ],
                        )),
                    Expanded(
                        child: Row(
                          children: <Widget>[
                            Radio(
                                value: "2",
                                groupValue: rader,
                                onChanged: (val) {
                                  setState(() {
                                    rader = val;
                                  });
                                }),
                            FixedSizeText("卡车")
                          ],
                        )),
                  ],
                )),
            getColumn(
              "帮我送",
              child: Column(
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          child: FixedSizeText(
                            "路程",
                            style: TextStyle(color: Colors.black45),
                          ),
                        ),
                      ),
                      Expanded(
                        child: Container(
                          alignment: Alignment.topRight,
                          child: FixedSizeText("${range} km   "),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          child: FixedSizeText(
                            "跑腿费",
                            style: TextStyle(color: Colors.black45),
                          ),
                        ),
                      ),
                      Expanded(
                        child: Container(
                          alignment: Alignment.topRight,
                          child: FixedSizeText("${price} \$   "),
                        ),
                      )
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          child: FixedSizeText(
                            "预计送达时间",
                            style: TextStyle(color: Colors.black45),
                          ),
                        ),
                      ),
                      Expanded(
                        child: Container(
                          alignment: Alignment.topRight,
                          child: FixedSizeText("${int.parse(longTime) + 20} 分钟  "),
                        ),
                      )
                    ],
                  )
                ],
              ),
            ),
            getColumn(
              "描述物品及备注",
              child: Column(
                children: <Widget>[
                  Container(
                    child: TextField(
                      controller: _remarks,
                      maxLines: 4,
                      decoration: InputDecoration(border: InputBorder.none),
                    ),
                  )
                ],
              ),
            ),
          ],
        );
      }
    } else {
      return Center(child: LoadingJumpingLine.square());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: BaseViewBar(
          childView: BaseTitleBar(
            "提交订单",
            leftIcon: Icons.clear,
          ),
          preferredSize: Size.fromHeight(50.0),
        ),
        body: Stack(
          children: <Widget>[
            getBody(),
            Positioned(
              bottom: 0,
              width: MediaQuery.of(context).size.width,
              child: Container(
                padding: EdgeInsets.all(10),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(17)),
                    boxShadow: [
                      BoxShadow(
                        color: Color(000000),
                        blurRadius: 5.0,
                      ),
                    ],
                    color: Colors.white),
                child: Row(
                  children: <Widget>[
                    Expanded(
                      flex: 7,
                      child: Row(
                        children: <Widget>[
                          Container(
                            padding: EdgeInsets.only(left: 10),
                            child: FixedSizeText(
                              "${price ?? ''} \$",
                              style: TextStyle(
                                  fontSize: 24,
                                  color: Colors.orange,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                          GestureDetector(
                            child: FixedSizeText(
                              "  费用详细 >",
                              style: TextStyle(
                                  fontSize: 12, fontWeight: FontWeight.bold),
                            ),
                          )
                        ],
                      ),
                    ),
                    Expanded(
                        flex: 3,
                        child: Center(
                          child: RaisedButton(
                            //提交按钮
                            color: Colors.lightBlueAccent,
                            highlightColor: Colors.blueAccent,
                            splashColor: Colors.blue,
                            colorBrightness: Brightness.dark,
                            shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10)),
                            onPressed: () async {
                              showDialog<Null>(
                                context: context, //BuildContext对象
                                barrierDismissible: false,
                                builder: (BuildContext context) {
                                  return LoadingDialog(
                                    //调用对话框
                                    text: 'Loding...',
                                  );
                                },
                              );
                              orderData data = orderData();
                              data.begin = "${begin.address} ${begin.remark}";
                              data.end = "${end.address} ${end.remark}";
                              data.endName = end.name;
                              data.distance = double.parse(range);
                              data.money = price;
                              data.beginLat = begin.lat;
                              data.beginLng = begin.lng;
                              data.endLng = end.lng;
                              data.endLat = end.lat;
                              data.estimatedTime = n.toString().substring(0,19);
                              data.fromId = int.parse(await SPUtils.get("UID"));
                              data.fromName = begin.name;
                              data.orderType = "0";
                              data.status = "2";
                              data.remark = _remarks.text.trim();
                              await DioUtils.orderAdd(data)
                                  .then((OrderEntity orderEntity) {
                                Get.back();
                                if (orderEntity.code == 500) {
                                  Toast.toast(context,
                                      msg: "请稍后重试", bgColor: Colors.redAccent);
                                  print("发起订单发生错误： ${orderEntity.msg}");
                                } else if (orderEntity.code == 0) {
//                                  Get.to(PayList(
//                                    orderdata: orderEntity.data,
//                                  ));
                                } else {
                                  Toast.toast(context,
                                      msg: "发生未知原因错误",
                                      bgColor: Colors.redAccent);
                                }
                              });
//                              Get.to(PayList());
                            },
                            child: FixedSizeText(
                              '下单',
                              style:
                                  TextStyle(color: Colors.white, fontSize: 15),
                            ),
                          ),
                        ))
                  ],
                ),
              ),
            ),
          ],
        ));
  }
}

Widget getColumn(String title, {Widget child}) {
  return Container(
    margin: EdgeInsets.only(top: 10, right: 10, left: 10),
    padding: EdgeInsets.fromLTRB(20.0, 15.0, 10.0, 20.0),
    decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(17),
        border: Border.all(color: Colors.white, width: 1),
        color: Colors.white),
    child: Column(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(bottom: 5),
          padding: EdgeInsets.only(bottom: 5),
          width: double.infinity,
          decoration: BoxDecoration(
              border:
                  Border(bottom: BorderSide(width: 1, color: Color(0xffe5e5e5)))
//                  border: Border(bottom:BorderSide(width: 1,color: Color(0xffe5e5e5))
              ),
          child: FixedSizeText(
            title,
            style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          ),
          alignment: Alignment.topLeft,
        ),
        child
      ],
    ),
  );
}
